package cc.mrbird.febs.common.filter;

import cc.mrbird.febs.common.annotation.Desensitized;
import cc.mrbird.febs.common.authentication.JWTUtil;
import cc.mrbird.febs.common.enums.SensitiveType;
import cc.mrbird.febs.common.utils.DesensitizedUtils;
import com.alibaba.fastjson.serializer.ValueFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class ValueDesensitizeFilter implements ValueFilter {

    @Override
    public Object process(Object object, String name, Object value) {
        //获取当前用户
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        List<String> dataScope = new ArrayList<>();
        if (StringUtils.isNotBlank(token)) {
            dataScope.addAll(Arrays.asList(JWTUtil.getDataScopeId(token)));
        }

        if (!(value instanceof String) || ((String) value).length() == 0) {
            return value;
        }
        try {
            List<Field> clsFields = new ArrayList<>();
            clsFields.addAll(Arrays.asList(object.getClass().getDeclaredFields()));
            clsFields.addAll(Arrays.asList(object.getClass().getSuperclass().getDeclaredFields()));
            Field field = null;
            if(clsFields.size() > 0) {
                for (Field clsField : clsFields) {
                    if(clsField.getName().equals(name)) {
                        field = clsField;
                    }
                }
            }
            Desensitized desensitization;
            if (null == field || String.class != field.getType() || dataScope.contains("1") || (desensitization = field.getAnnotation(Desensitized.class)) == null) {
                return value;
            }
            String valueStr = (String) value;
            SensitiveType type = desensitization.type();
            switch (type) {
                case ID_CARD:
                    valueStr = DesensitizedUtils.idCardNum(valueStr);
                    return valueStr;
                case MOBILE:
                    valueStr = DesensitizedUtils.mobilePhone(valueStr);
                    return valueStr;
                case POLITICS:
                    valueStr = DesensitizedUtils.politics(valueStr);
                    return valueStr;
                case ADDRESS:
                    valueStr = DesensitizedUtils.address(valueStr, valueStr.length());
                    return valueStr;
                case CULTURE:
                    valueStr = DesensitizedUtils.culture(valueStr);
                    return valueStr;
                default:
            }
        } catch (Exception e) {
            log.error("当前数据类型为{},值为{}", object.getClass(), value);
            return value;
        }
        return value;
    }
}
